package org.sraosha.microservice.oauth2.service.impl;

import org.sraosha.framework.dto.ServiceResult;
import org.sraosha.framework.enumeration.ServiceResultEnum;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.sraosha.microservice.oauth2.mapper.UserMapper;
import org.sraosha.microservice.oauth2.model.User;
import org.sraosha.microservice.oauth2.service.UserService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * UserService接口的实现类
 */
@Slf4j
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 根据用户名，返回用户信息
     *
     * @param username
     * @return
     */
    public ServiceResult<User> findUserByUserName(String username) {
        User user = serviceHelper.getUserMapper().findUserByUserName(username);

        ServiceResult<User> serviceResult = new ServiceResult<User>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(user);
        serviceResult.setMessage(ServiceResultEnum.SELECT_SUCCESS.getMessage());
        serviceResult.setCode(ServiceResultEnum.SELECT_SUCCESS.getCode());
        return serviceResult;
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public ServiceResult<User> add(User user) {
        serviceHelper.getUserMapper().insert(user);

        ServiceResult<User> serviceResult = new ServiceResult<User>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(user);
        serviceResult.setMessage(ServiceResultEnum.INSERT_SUCCESS.getMessage());
        serviceResult.setCode(ServiceResultEnum.INSERT_SUCCESS.getCode());
        return serviceResult;
    }

    /**
     * 添加用户，username不能重名
     * @param user
     * @return
     */
    @Override
    public ServiceResult<User> addWithoutDuplicateUsername(User user) {
        User theUser = serviceHelper.getUserMapper().findUserByUserName(user.getUsername());
        if (null == theUser){
            serviceHelper.getUserMapper().insert(user);

            ServiceResult<User> serviceResult = new ServiceResult<User>();
            serviceResult.setSuccess(Boolean.TRUE);
            serviceResult.setResult(user);
            serviceResult.setMessage(ServiceResultEnum.INSERT_SUCCESS.getMessage());
            serviceResult.setCode(ServiceResultEnum.INSERT_SUCCESS.getCode());
            return serviceResult;
        } else {
            ServiceResult<User> serviceResult = new ServiceResult<User>();
            serviceResult.setSuccess(Boolean.FALSE);
            serviceResult.setMessage(ServiceResultEnum.INSERT_FAIL.getMessage());
            serviceResult.setCode(ServiceResultEnum.INSERT_FAIL.getCode());
            return serviceResult;
        }
    }
}
